package org.jeecg.modules.rental.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.rental.entity.Assets;
import org.jeecg.modules.rental.resp.AssetInfoResponse;
import org.jeecg.modules.rental.service.IAssetsService;
import org.jeecg.modules.rental.service.IInvestorProfitsService;
import org.jeecg.modules.rental.service.IPlatformProfitsService;
import org.jeecg.modules.rental.service.ISiteProfitsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 资产表
 * @Author: jeecg-boot
 * @Date:   2025-02-28
 * @Version: V1.0
 */
@Api(tags="资产表")
@RestController
@RequestMapping("/rental/assets")
@Slf4j
public class AssetsController extends JeecgController<Assets, IAssetsService> {
	@Autowired
	private IAssetsService assetsService;

	@Autowired
	private IPlatformProfitsService platformProfitsService;

	 @Autowired
	 private IInvestorProfitsService investorProfitsService;

	 @Autowired
	 private ISiteProfitsService siteProfitsService;

	
	/**
	 * 分页列表查询
	 *
	 * @param assets
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "资产表-分页列表查询")
	@ApiOperation(value="资产表-分页列表查询", notes="资产表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<Assets>> queryPageList(Assets assets,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Assets> queryWrapper = QueryGenerator.initQueryWrapper(assets, req.getParameterMap());
		Page<Assets> page = new Page<Assets>(pageNo, pageSize);
		IPage<Assets> pageList = assetsService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param assets
	 * @return
	 */
	@AutoLog(value = "资产表-添加")
	@ApiOperation(value="资产表-添加", notes="资产表-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:assets:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody Assets assets) {
		assetsService.save(assets);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param assets
	 * @return
	 */
	@AutoLog(value = "资产表-编辑")
	@ApiOperation(value="资产表-编辑", notes="资产表-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:assets:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody Assets assets) {
		assetsService.updateById(assets);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "资产表-通过id删除")
	@ApiOperation(value="资产表-通过id删除", notes="资产表-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.demo:assets:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		assetsService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "资产表-批量删除")
	@ApiOperation(value="资产表-批量删除", notes="资产表-批量删除")
	//@RequiresPermissions("org.jeecg.modules.demo:assets:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.assetsService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "资产表-通过id查询")
	@ApiOperation(value="资产表-通过id查询", notes="资产表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Assets> queryById(@RequestParam(name="id",required=true) String id) {
		Assets assets = assetsService.getById(id);
		if(assets==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(assets);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param assets
    */
    //@RequiresPermissions("org.jeecg.modules.demo:assets:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Assets assets) {
        return super.exportXls(request, assets, Assets.class, "资产表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("assets:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Assets.class);
    }

		 @ApiOperation("获取资产信息")
		 @GetMapping("/getAssetInfo")
		 public Result<AssetInfoResponse> getAssetInfo() {
			 try {
				 // 获取当前登录用户的信息
				 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

				 // 调用 Service 查询资产信息
				 AssetInfoResponse assetInfo = assetsService.getAssetInfo(sysUser.getId());

				 // 如果资产信息不存在，初始化一条数据
				 if (assetInfo == null) {
					 // 初始化资产信息
					 Assets newAsset = new Assets();
					 newAsset.setId(null); // 主键使用数据库自增或通过分配策略生成
					 newAsset.setCreateBy(sysUser.getUsername());
					 newAsset.setCreateTime(new java.util.Date());
					 newAsset.setOwnerId(Integer.parseInt(sysUser.getId())); // 设置当前用户 ID 为资产归属者
					 newAsset.setOwnerType("user"); // 假定资产归属类型为 "user"
					 newAsset.setTotalRevenue(BigDecimal.ZERO); // 初始化总收益为 0
					 newAsset.setTotalBalance(BigDecimal.ZERO); // 初始化总余额为 0
					 newAsset.setAssetType("other"); // 初始化资产类型为 "other"
					 newAsset.setTotalInvestment(BigDecimal.ZERO); // 初始化总投资金额为 0

					 // 保存初始化的数据到数据库
					 assetsService.save(newAsset);

					 // 转换为响应对象
					 assetInfo = assetsService.getAssetInfo(sysUser.getId());
				 }

				 return Result.OK(assetInfo);
			 } catch (Exception e) {
				 e.printStackTrace();
				 return Result.error("查询失败：" + e.getMessage());
			 }
		 }



	 @ApiOperation("我的收益统计")
	 @GetMapping("/getMyIncomeStatistics")
	 public Result<List<Map<String, Object>>> getMyIncomeStatistics(
			 @RequestParam(name = "type", defaultValue = "month") String type,
			 @RequestParam(name = "roleCode", required = true) String roleCode) { // 增加角色参数
		 try {
			 // 获取当前登录的用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if (sysUser == null) {
				 return Result.error("用户未登录");
			 }

			 // 调用 Service 获取收益统计数据
			 List<Map<String, Object>> incomeStatistics;
			 if ("investor".equals(roleCode)) {
				 // 投资者角色查询
				 incomeStatistics = investorProfitsService.getIncomeStatistics(sysUser.getId(), type);
			 } else if ("platform".equals(roleCode)) {
				 // 管理员角色查询
				 incomeStatistics = platformProfitsService.getPlatformIncomeStatistics( type);

			 } else if ("site".equals(roleCode)) {
				 // 其他角色或未匹配的角色
				 incomeStatistics = siteProfitsService.getSiteProfitsStatistics( type);

			 }else {
				 return Result.error("当前角色不支持收益统计功能");
			 }

			 return Result.OK(incomeStatistics);
		 } catch (Exception e) {
			 log.error("获取我的收益统计失败", e);
			 return Result.error("获取收益统计失败：" + e.getMessage());
		 }
	 }

}
